/********************************************************************************************
 *
 ********************************************************************************************/
#include <includes.h>
#include <LPC17xx.h>
#include <core_cm3.h>
#include <system_LPC17xx.h>
#include <lpc17xx_pinsel.h>
#include <lpc17xx_i2c.h>
#include <at24cxx.h>
#include <SSD1298_driver.h>
#include <LCD_task.h>

const uint8_t I2CInfo[] = "AT24C02 Test\0";
uint8_t I2CTestBuf[256];
uint8_t I2CTestSt;

void I2CEntry()
{
	uint16_t Cnt;
	Cnt = 2;
	while(Cnt --)
	{
		I2CTestBuf[Cnt] = 0;
		while(At24cRead(Cnt*256,256,I2CTestBuf) != 0);
		while(At24cRead(Cnt*256,1,I2CTestBuf) != 0);
		Cnt = Cnt;
	}
	
	Cnt = 64;
	I2CTestSt ++;
}

void I2C_Task(void * p_arg)
{
    OS_ERR err;
//  PINSEL_CFG_Type *PinCfg; 
    
	uint16_t Cnt;
	uint8_t  CntIn;
    
    p_arg = p_arg;
    /****************************************************
    PinCfg->Portnum   = PINSEL_PORT_0 ;
    PinCfg->Pinnum    = PINSEL_PIN_27 ;
    PinCfg->Funcnum   = PINSEL_FUNC_1 ;
    PinCfg->Pinmode   = PINSEL_PINMODE_TRISTATE  ;
    PinCfg->OpenDrain = PINSEL_PINMODE_OPENDRAIN ;
    PINSEL_ConfigPin(PinCfg); 
    
    PinCfg->Portnum   = PINSEL_PORT_0 ;
    PinCfg->Pinnum    = PINSEL_PIN_28 ;
    PinCfg->Funcnum   = PINSEL_FUNC_1 ;
    PinCfg->Pinmode   = PINSEL_PINMODE_TRISTATE  ;
    PinCfg->OpenDrain = PINSEL_PINMODE_OPENDRAIN ;
    PINSEL_ConfigPin(PinCfg);  
    ****************************************************/
	I2CTestSt = 0;
    LPC_PINCON->PINSEL1 &= ~(0x03UL << 22);  // P0.27
    LPC_PINCON->PINSEL1 |=  (0x01UL << 22);
    LPC_PINCON->PINSEL1 &= ~(0x03UL << 24);  // P0.28
    LPC_PINCON->PINSEL1 |=  (0x01UL << 24);
    PINSEL_SetI2C0Pins(PINSEL_I2C_Normal_Mode, ENABLE);
    
    I2C_Init(LPC_I2C0, 100000u);                //Give Power to the modle , and set clockrate ; 
    I2C_Cmd(LPC_I2C0, I2C_MASTER_MODE, ENABLE); //Enable I2c0 and set it to be master mode;

    NVIC_DisableIRQ(I2C0_IRQn);
    NVIC_SetPriority(I2C0_IRQn, 0x80);
    
	I2CTestSt = 1;
	
			

	CntIn = 255;
	do{
		I2CTestBuf[CntIn] = CntIn;
	}while(CntIn--);		
	while(At24cWrite(0,256,I2CTestBuf) != 0 ){};
	CntIn = 255;
	do{
		I2CTestBuf[CntIn] += 0x80;
	}while(CntIn--);
	while(At24cWrite(256,256,I2CTestBuf) != 0 ){};
	
	I2CTestSt = 5;		
	Cnt = 64;
	while(Cnt --)
		I2CTestBuf[Cnt] = 0;
	
	Cnt = 0;                                             //Read data to display buffer
	do{
		LCD_String_I2C.Data[Cnt] = I2CInfo[Cnt] ;
		if(Cnt > 28)
			{
				LCD_String_I2C.Data[28] = '\0';
				break;
			}
	}while(I2CInfo[Cnt ++] != '\0');

	LCD_String_I2C.StartX     = 9*8;
	LCD_String_I2C.StartY     = 5*16;
	LCD_String_I2C.BackColor  = Blue;
	LCD_String_I2C.PointColor = White;
	LCD_String_I2C.OnOff      = DISPLAY_ON ;
    
    
    while(1)
    {
        OSTimeDly(200,OS_OPT_TIME_DLY,&err);
		I2CEntry();
    }
}
